package com.spice.im.jspeex.voice;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.util.Log;
public class ARecorder {
	private static final String TAG = "ARecorder";
	Object mLock;
	private double volume = 0;
	public ARecorder() {
		mLock = new Object();
	}
	public double getAmplitude(){
		return volume;
	} 
	/**
	 * 安卓录音的时候是使用AudioRecord来进行录制的（当然mediarecord也可以，mediarecord强大一些），
	 * 录制后的数据称为pcm，这就是raw（原始）数据，这些数据是没有任何文件头的，存成文件后用播放器是
	 * 播放不出来的，需要加入一个44字节的头，就可以转变为wav格式，这样就可以用播放器进行播放了
	 */
	public static final int SAMPLE_RATE = 16000;
	public static final int CHANNELS = 1;
	public AudioRecord mRecorder;
	private byte[] mBuffer;
	public boolean mIsRecording = false;
	public void initRecorder() {
		int bufferSize = AudioRecord.getMinBufferSize(SAMPLE_RATE, AudioFormat.CHANNEL_IN_MONO,
				AudioFormat.ENCODING_PCM_16BIT);
		mBuffer = new byte[bufferSize];
		mRecorder = new AudioRecord(MediaRecorder.AudioSource.MIC, SAMPLE_RATE, AudioFormat.CHANNEL_IN_MONO,
				AudioFormat.ENCODING_PCM_16BIT, bufferSize);
	}
	public void startBufferedWrite(final File file) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				DataOutputStream output = null;
				try {
					output = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
					while (mIsRecording) {
						int readSize = mRecorder.read(mBuffer, 0, mBuffer.length);
						long v = 0;
				        // 将 buffer 内容取出，进行平方和运算
				        for (int i = 0; i < mBuffer.length; i++) {
				            v += mBuffer[i] * mBuffer[i];
				        }
				        // 平方和除以数据总长度，得到音量大小。
				        double mean = v / (double) readSize;
//				        volume = 10 * Math.log10(mean);
				        volume = Math.log10(mean);
				        Log.d(TAG+"============分贝值:===========>", "分贝值:" + volume);
				        // 大概一秒十次
				        synchronized (mLock) {
				            try {
				                mLock.wait(100);
				            } catch (InterruptedException e) {
				              e.printStackTrace();
				            }
				        }
				          
						for (int i = 0; i < readSize; i++) {
							output.writeByte(mBuffer[i]);
						}
					}
				} catch (IOException e) {
//					Toast.makeText(JSpeexSampleActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
					e.printStackTrace();
				} finally {
					if (output != null) {
						try {
							output.flush();
						} catch (IOException e) {
//							Toast.makeText(JSpeexSampleActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
							e.printStackTrace();
						} finally {
							try {
								output.close();
							} catch (IOException e) {
//								Toast.makeText(JSpeexSampleActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
								e.printStackTrace();
							}
						}
					}
				}
			}
		}).start();
	}
	/**注意启动：
	 * initRecorder();
	 * initEncoder();
	 * mIsRecording = true;
	 * mRecorder.startRecording();
	 * mRawFile = getFile("raw");
	 * startBufferedWrite(mRawFile);
	 * */
	/**注意停止：
	 * mIsRecording = false;
	 * mRecorder.stop();
	 * mRecorder.release();
	 * mRecorder = null;
	 * mEncodedFile = getFile("spx");
					try {
						encodeFile(mRawFile, mEncodedFile);
					} catch (IOException e) {
						Toast.makeText(JSpeexSampleActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
					}*/
	
}
